package fudan.secret.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.opensymphony.xwork2.ActionSupport;

import fudan.secret.domain.Follow;
import fudan.secret.util.HibernateSessionFactory;

public class FollowAction extends ActionSupport{
  private int uid_1;
  private int uid_2;
  private int flag;
  private Map<String,String> map;
  
  @JSON(serialize=false)
  public int getUid_1(){
	  return uid_1;
  }
  
  public void setUid_1(int id1){
	  uid_1 = id1;
  }
  
  @JSON(serialize=false)
  public int getUid_2(){
	  return uid_2;
  }
  
  public void setUid_2(int id2){
	  uid_2 = id2;
  }
  
  @JSON(serialize=false)
  public int getFlag(){
	  return flag;
  }
  
  public void setFlag(int flag){
	  this.flag = flag;
  }
  
  public Map<String, String> getResult() {  
      return map;  
   }  
  
  public String execute() throws Exception{
	  Session session = HibernateSessionFactory.getSession();
	  Transaction tx = null;
	  map = new HashMap<String,String>();
	  try{
		  String hql ="from Follow where uid_1= :uid_1 and uid_2= :uid_2";
		  Query query = session.createQuery(hql);
		  query.setParameter("uid_1", uid_1);
		  query.setParameter("uid_2", uid_2);
		  Follow follow = (Follow) query.uniqueResult();
		  if(flag == 1){
			  if(follow == null){
				  Follow newfollows = new Follow();
				  newfollows.setuid_1(uid_1);
				  newfollows.setuid_2(uid_2);
				  tx = session.beginTransaction();
				  session.saveOrUpdate(newfollows);
				  tx.commit();
				  map.put("follow", "true");
			  }else{
				  map.put("follow", "dupicated");
				  return SUCCESS;
			  }
		  }else if(flag == 0){
			  if(follow == null){
				  map.put("follow", "notfollow");
				  return SUCCESS;
			  }else{
				  tx = session.beginTransaction();
				  session.delete(follow);
				  tx.commit();
				  map.put("follow", "true");
			  }
		  }
	  } catch(Exception e) {
		  map.put("login", "error");
		  e.printStackTrace();
		  tx.rollback();
	  } finally {
		  session.close();
	  }
	  return SUCCESS;
  }
  
  
}
